package com.stox.ui.javafx.core.widget;

import java.util.Collection;

import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ProgressIndicator;

public abstract class LazyLoadingMenu extends Menu{

	private boolean childrenLoaded = false;
	
	public LazyLoadingMenu() {
		MenuItem loadingMenuItem = new MenuItem();
		ProgressIndicator progressIndicator = new ProgressIndicator();
		loadingMenuItem.setGraphic(progressIndicator);
		getItems().add(loadingMenuItem);
		
		setOnShowing(new EventHandler<Event>(){
		@Override
		public void handle(Event event) {
			ObservableList<MenuItem> items = getItems();
			if(!childrenLoaded){
				Collection<MenuItem> menuItems = loadMenuItems();
				getItems().clear();
				if(null != menuItems && !menuItems.isEmpty()){
					items.addAll(menuItems);
				}
				childrenLoaded = true;
			}
		}
		});
	}
	
	public abstract Collection<MenuItem> loadMenuItems();
	
}
